package com.example.homework.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.location.Address;

import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.homework.R;
import com.example.homework.entity.NowWeatherInfo;
import com.example.homework.utils.JsonUtils;

import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 *
 * 实时天气示例
 *
 * 和风天气开发 https://dev.qweather.com/docs/api/weather/
 */
public class RealTimeWeatherActivity extends AppCompatActivity  implements LocationListener {

    private TextView nowAddress;
    private TextView lat;
    private TextView lon;
    // 定义双精度类型的经纬度
    private Double longitude,latitude;
    // 定义位置管理器
    private LocationManager locationManager;
    ImageView iv_weatherIcon;
    TextView tv_temp,tv_weatherText,tv_wind,tv_hum;
    EditText et_city;
    NowWeatherInfo nowWeather;

    /**
     *   和风天气项目定义 API_KEY
     */
    private static final String KEY = "31d06a00723e45c5bb6d769d93baeae1";

    private static final String BASE_URL = "https://devapi.qweather.com/v7/weather/";

    private static final String TAG = RealTimeWeatherActivity.class.getName();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_real_time_weather);
        // 得到对应视图ID
        nowAddress = findViewById(R.id.tv_nowAddress);
        lat = findViewById(R.id.tv_latitude);
        lon = findViewById(R.id.tv_longitude);

        // 判断当前是否拥有使用GPS的权限
        if (ActivityCompat.checkSelfPermission(RealTimeWeatherActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            // 申请权限
            ActivityCompat.requestPermissions(RealTimeWeatherActivity.this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, 100);
        }
        getLocation();
        initView();
    }


    public void onClickQueryCityButton(View view){
       String city = et_city.getText().toString();
       if (!Objects.isNull(city) && !"".equals(city)){
           getCityInfo(city);
       }else {
           Toast.makeText(RealTimeWeatherActivity.this,"请输入城市名称",Toast.LENGTH_LONG).show();
       }
    }



    /***
     *
     * https://geoapi.qweather.com/v2/city/lookup?location=武汉
     * @param queryCity
     * @return
     */
    public String getCityInfo(String queryCity){

        String cityQueryUrl = "https://geoapi.qweather.com/v2/city/lookup?key=" + KEY + "&" +"location="+queryCity;
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(cityQueryUrl)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG, "getCity Info : error"+e.getLocalizedMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Log.d(TAG, "getCityInfo:"+response);
                if (response.isSuccessful()) {
                    String resultResponse = response.body().string();
                    String locationId = JsonUtils.parseCityLocationId(resultResponse);
                    Log.i(TAG,"locationId"+locationId);
                    if (!Objects.isNull(locationId)  &&  !"".equals(locationId)){
                        getNowWeatherInfo(locationId);
                    }
                }
            }
        });
        return null;
    }


    /**
     * 获取实时天气
     * @param locationID
     * @return
     */
    public  String getNowWeatherInfo(String locationID) {
        String resultResponse = "";
        String locationUrl = BASE_URL + "now" + "?" + "key=" + KEY + "&" +"location=" + locationID
                + "&" + "lang=" + "zh";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(locationUrl)
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG, "getNowWeatherInfo: error");
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Log.d(TAG, "getNowWeatherInfo:"+response);
                if (response.isSuccessful()) {
                    String resultResponse = response.body().string();
                    Log.d(TAG, "getNowWeatherInfo: " + resultResponse);
                    NowWeatherInfo info = JsonUtils.parseNowWeatherJson(resultResponse);
                    //渲染到界面
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setView( info);
                        }
                    });
                }
            }
        });

        return resultResponse;
    }


    //定位信息
    @Override
    public void onLocationChanged(@NonNull Location location) {
        // 获取当前纬度
        latitude = location.getLatitude();
        // 获取当前经度
        longitude = location.getLongitude();
        lat.setText("纬度：" + latitude);
        lon.setText("经度：" + longitude);
        // 定义位置解析
        Geocoder geocoder = new Geocoder(RealTimeWeatherActivity.this, Locale.getDefault());
        try {
            List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
            // 得到第一个经纬度位置解析信息
            Address address = addresses.get(0);
            // 获取到详细的当前位置
            // Address里面还有很多方法你们可以自行实现去尝试。比如具体省的名称、市的名称...
            String info = address.getAddressLine(0) + // 获取国家名称
                    address.getAddressLine(1) + // 获取省市县(区)
                    address.getAddressLine(2);  // 获取镇号(地址名称)

            // 赋值
            nowAddress.setText(info);
        } catch (IOException e) {
            e.printStackTrace();
        }
        locationManager.removeUpdates(this);

        //通过经纬度 来查询天气 英文逗号分隔的经度,纬度坐标（十进制，最多支持小数点后两位）
        String  locationInfo = String.format("%.2f",longitude)+","+String.format("%.2f",latitude);
        Log.i(TAG,"locationInfo:"+locationInfo);
        String resultResponse =  getNowWeatherInfo(locationInfo);

    }

    @SuppressLint("MissingPermission")
    private void getLocation() {
        // 获取当前位置管理器
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // 启动位置请求
        // LocationManager.GPS_PROVIDER GPS定位
        // LocationManager.NETWORK_PROVIDER 网络定位
        // LocationManager.PASSIVE_PROVIDER 被动接受定位信息
        locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, RealTimeWeatherActivity.this);
    }


    private void initView() {
        iv_weatherIcon =findViewById(R.id.weatherIcon);
        tv_temp = findViewById(R.id.temp);
        tv_weatherText=findViewById(R.id.weatherText);
        tv_wind = findViewById(R.id.wind);
        tv_hum = findViewById(R.id.hum);
        et_city = findViewById(R.id.et_city);
    }


    private void setView(NowWeatherInfo nowWeather){
        iv_weatherIcon.setImageDrawable(GetImageByStringId("w"+nowWeather.getIcon()));
        tv_temp.setText(nowWeather.getTemp()+"℃");
        tv_weatherText.setText(nowWeather.getText());
        tv_wind.setText(nowWeather.getWindScale() +"级\n"+ nowWeather.getWindDir());
        tv_hum.setText(nowWeather.getHumidity()+"%\n相对湿度");
    }

    public Drawable GetImageByStringId(String name) {
        int resID = getResources().getIdentifier(name, "drawable", "com.example.homework");
        Drawable image =  getResources().getDrawable(resID);
        return image;
    }


}